package index

import (
	"encoding/json"
	"errors"
	"io"
	"io/ioutil"
	"net/http"
	"strings"

	"xp/lib/etc"
)

var (
	target = NewLB(strings.Split(etc.Str("index", "target"), ","))
)

type Resp struct {
	Error bool            `json:"error"`
	Items json.RawMessage `json:"items"`
}

func Bulk(body io.Reader) error {
	resp, err := http.Post(target.Get()+"_bulk", "application/json", body)
	if resp != nil && resp.Body != nil {
		defer resp.Body.Close()
	}
	if err != nil {
		return err
	}
	if resp.StatusCode > 201 {
		io.Copy(ioutil.Discard, resp.Body)
		return errors.New("HTTP error:  " + resp.Status)
	}
	var r Resp
	if err := json.NewDecoder(resp.Body).Decode(&r); err != nil {
		return err
	}
	if r.Error {
		return errors.New(string(r.Items))
	}
	return nil
}
